﻿using CommunityToolkit.Mvvm.ComponentModel;
using CommunityToolkit.Mvvm.Input;
using PrismProject01.Services;
using PrismProject01.Views;
using SourceGeneratorAttribute;
using System.Collections.ObjectModel;
using System.ComponentModel.DataAnnotations;
using System.Windows;


namespace PrismProject01.ViewModels {
    public partial class MainWindowViewModel(ICustomerStore _customerStore, IDialogService _dialogService) : ObservableValidator {
        #region 可通知属性定义
        public ObservableCollection<string> Customers { get; private set; } = new();

        private string? _selectedCustomer = null;
        public string? SelectedCustomer {
            get => _selectedCustomer;
            set {
                if (SetProperty(ref _selectedCustomer, value)) {
                    MessageBox.Show(SelectedCustomer ?? "SelectedCustomer为空");
                }
            }
        }

        [ObservableProperty]
        [RegularExpression(@"^\d+$", ErrorMessage = "年龄必须为非负整数")]
        [Required(ErrorMessage = "年龄不能为空")]
        [NotifyDataErrorInfo]
        [GenerateIntValue]
        private string _age = "32";
        #endregion


        #region 命令逻辑定义
        [RelayCommand]
        private void LoadData() {
            Customers.Clear();
            Customers.AddRange(_customerStore.GetAll());
        }

        [RelayCommand]
        private void ValidateData() {
            ValidateProperty(Age, nameof(Age));
            if (HasErrors) {
                var errors = string.Join(Environment.NewLine, GetErrors().Select(e => e.ErrorMessage).ToList().Distinct());
                MessageBox.Show(errors);
                ClearErrors();
                return;
            }
            MessageBox.Show($"Age={AgeValue ?? 0}");
        }

        [RelayCommand]
        private void ShowDialog() {
            DialogParameters parameters = new();
            parameters.Add("title", "弹窗测试");
            parameters.Add("dollar", 100);
            _dialogService.ShowDialog(nameof(WarningDialog), parameters, callback => {
                if (callback.Result == ButtonResult.OK) {
                    MessageBox.Show($"$100={callback.Parameters.GetValue<int>("rmb")}RMB");
                }
            });
        }
        #endregion
    }
}
